# 3.8 renderFile file download
# 1. Basic Usage of renderFile
The renderFile
series of methods are used for file downloads.
The renderFile
method uses a baseDownloadPath
parameter as the base path to locate the file. In a standard maven project setup, this parameter defaults to the directory: src/main/webapp/download
.
Here's how to use it under the default configuration:
// The final downloaded file will be: src/main/webapp/download/file.zip
renderFile("file.zip");
// The final downloaded file will be: src/main/webapp/download/abc/def/file.zip
renderFile("abc/deb/file.zip");
2
3
4
5
As shown above, the final downloaded file is always: baseDownloadPath
+ the parameter passed into renderFile
.
The existence of baseDownloadPath
effectively fixes a base path. renderFile
always uses this path as the base to locate the file.
# 2. Configuring baseDownloadPath
baseDownloadPath
can also be freely configured in configConstant(Constants me)
. For example:
me.setBaseDownloadPath("files");
In the context of a standard maven project, the baseDownloadPath
value from the configuration above will point to the directory src/main/webapp/files
.
Additionally, baseDownloadPath
can also be configured as an absolute path, allowing it to point outside the project. For example:
// For Linux/Mac systems, paths starting with "/" are absolute paths.
me.setBaseDownloadPath("/var/download");
// For Windows systems, paths starting with a drive letter are also absolute paths.
me.setBaseDownloadPath("D:/download");
2
3
4
5
In the configuration above, in Linux, paths that start with "/" are considered absolute. So, renderFile
will look for the download file under the "/var/download" path.
This kind of configuration allows separation between project resources and download resources. It's also beneficial for cluster deployment (single-machine multi-instance deployment) where multiple nodes can share the same directory and the same set of downloadable files.
# 3. renderFile(File file)
The renderFile(File file)
method directly uses the File
parameter to get the download file, freeing it from the constraints of baseDownloadPath
. It can point to a file located anywhere, like:
String file = "D:/my-project/share/files/jfinal-all.zip";
renderFile(new File(file));
2
As shown, the File
points to a file at an arbitrary location, bypassing the constraints of baseDownloadPath
.
# 4. Renaming the Download File
If you don't want to use the original filename of the download file, you can specify a new download filename:
renderFile("OldFileName.txt", "NewFileName.txt");
In this way, users downloading the file will see it as "NewFileName.txt", regardless of its original name on the server.